﻿using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using AirCtrl.Wpf.Core;
using MessageBox = HandyControl.Controls.MessageBox;

namespace AirCtrl.Wpf.Views;

public partial class CaptureViewModel : ObservableObject
{
    [ObservableProperty] private bool _isCapturing;
    [ObservableProperty] private double _intervalSeconds = 5;

    private Timer _timer;
    private ObservableCollection<CameraViewModel> _cameraViewModels;


    public CaptureViewModel(ObservableCollection<CameraViewModel> cameraViewModels)
    {
        _cameraViewModels = cameraViewModels;
    }

    [RelayCommand]
    private async Task StartCapture()
    {
        _timer = new Timer(TimerCallBack, null, 0, (int)(IntervalSeconds * 1000));
        var res = await CmdGroundClient.Instance.StartCapture(IntervalSeconds);
        if (res) IsCapturing = true;
        else MessageBox.Error("开启失败");
    }
    async void TimerCallBack(object state)
    {
        await Capture();
    }

    [RelayCommand]
    private async Task StopCapture()
    {
        _timer.Dispose();
        var res = await CmdGroundClient.Instance.StopCapture();
        if (res) IsCapturing = false;
    }

    [RelayCommand]
    private void OpenFolder()
    {
        var path = CaptureHelper.GetFolderPath();
        Process.Start("explorer.exe", path);
    }

    [RelayCommand]
    private async Task Capture()
    {
        var cameras = _cameraViewModels;
        foreach (var vmCamera in cameras)
        {
            if(vmCamera?.ImageSource == null) continue;

            var path = CaptureHelper.GetFileFullPath(vmCamera.Title);
            SaveImageSource(vmCamera.ImageSource, path);
        }
    }

    private void SaveImageSource(ImageSource imageSource, string filePath)
    {
        // 将 ImageSource 转换为 BitmapSource
        BitmapSource bitmapSource = imageSource as BitmapSource;
        if (bitmapSource == null)
        {
            // 如果是其他类型的 ImageSource（如 DrawingImage），需要先转换为 BitmapSource
            RenderTargetBitmap rtb = new RenderTargetBitmap(
                (int)imageSource.Width,
                (int)imageSource.Height,
                96, 96, PixelFormats.Pbgra32);

            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext dc = dv.RenderOpen())
            {
                dc.DrawImage(imageSource, new Rect(0, 0, imageSource.Width, imageSource.Height));
            }

            rtb.Render(dv);
            bitmapSource = rtb;
        }

        // 创建编码器
        BitmapEncoder encoder = new JpegBitmapEncoder();
        /*switch (format)
        {
            case ImageFormat.Jpeg:
                encoder = new JpegBitmapEncoder();
                break;
            case ImageFormat.Gif:
                encoder = new GifBitmapEncoder();
                break;
            case ImageFormat.Tiff:
                encoder = new TiffBitmapEncoder();
                break;
            case ImageFormat.Png:
            default:
                encoder = new PngBitmapEncoder();
                break;
        }*/

        // 添加帧并保存
        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
        {
            encoder.Save(fileStream);
        }
    }
}